package com.lsy.weizhi2.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.model.GlideUrl;
import com.bumptech.glide.load.model.LazyHeaders;
import com.google.gson.Gson;
import com.lsy.weizhi2.JsonObject.ImageJson;
import com.lsy.weizhi2.JsonObject.UserInfo;
import com.lsy.weizhi2.R;
import com.lsy.weizhi2.config.Constants;
import com.lsy.weizhi2.config.MyHeight;
import com.lsy.weizhi2.config.MyInfo;
import com.lsy.weizhi2.customview.GlideCircleTransform;
import com.lsy.weizhi2.mybase.BaseApp;
import com.lsy.weizhi2.mybase.MyBaseActivity;
import com.lsy.weizhi2.mybase.MyTitleView;
import com.lsy.weizhi2.myutils.SendPhotoCall;
import com.lsy.weizhi2.myutils.TitleViewCall;
import com.lsy.weizhi2.picture.PicturePopup;
import com.lsy.weizhi2.picture.PictureUtils;
import com.lsy.weizhi2.utils.MyMethod;
import com.lsy.weizhi2.utils.MyOkHttpUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class CompleteInfo extends MyBaseActivity {
    private Context context;
    private MyTitleView complete_title;
    private int xx;
    private Handler handler = new Handler();
    private Gson gson;
    private EditText sex_et, age_et, QQ_mail_et, qianming_et;
    private TextView nick_name_et,mobile_et;
    private ImageView head_iv;
    private TextView complete_progress;
    private String name,email,phone,qianming;
    private int sex,age,avatar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_complete_info);
        context=CompleteInfo.this;
        Init();
    }

    private void Init() {
        complete_title = (MyTitleView) findViewById(R.id.complete_title);
        gson = new Gson();
        nick_name_et = (TextView) findViewById(R.id.nick_name_et);
        sex_et = (EditText) findViewById(R.id.sex_et);
        age_et = (EditText) findViewById(R.id.age_et);
        QQ_mail_et = (EditText) findViewById(R.id.QQ_mail_et);
        mobile_et = (TextView) findViewById(R.id.mobile_et);
        qianming_et = (EditText) findViewById(R.id.qianming_et);
        head_iv = (ImageView) findViewById(R.id.head_iv);
        complete_progress= (TextView) findViewById(R.id.complete_progress);
        head_iv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new PicturePopup().init(context, new SendPhotoCall() {
                    @Override
                    public void Request(String message) {
                        if (message != null) {
                            try {
                                Log.i("CompleteInfo", "message=s=image=" + message);
                                ImageJson imageJson = gson.fromJson(message, ImageJson.class);
                                avatar = imageJson.getData().getId();
                                Glide.with(context)
                                        .load(new GlideUrl(Constants.DOWN_USER_PICTURE+avatar,new LazyHeaders.Builder().addHeader("WZ-AUTH-TOKEN", MyInfo.Token).addHeader("WZ-AUTH-ID",MyInfo.User_Id+"").build()))
                                        .transform(new GlideCircleTransform(context))
                                        .error(R.mipmap.default_head)
                                        .into(head_iv);
                            } catch (Exception e) {
                                Log.i("CompleteInfo", "message=f=image=" + message);
                            }
                        }
                    }
                });
            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        GetInfo();
    }

    @Override
    protected void onResume() {
        super.onResume();
        xx = 0;
        ViewTreeObserver vto = complete_title.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                if (xx < 1) {
                    xx++;
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(complete_title.getLayoutParams());
                            params.height = MyHeight.ACTIONBAR + MyHeight.MyTitleHeight;
                            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                                complete_title.setLayoutParams(params);
                            }
                        }
                    });
                }
            }
        });
        complete_title.setTitleViewCall(new TitleViewCall() {
            @Override
            public void Click(View view, int flag) {
                if(flag==TitleViewCall.OK){
                    ResetInfo();
                }
            }
        });

    }

    private void ResetInfo(){
        email=QQ_mail_et.getText().toString().trim();
        qianming=qianming_et.getText().toString();
        age=Integer.parseInt(age_et.getText().toString());
        if(sex_et.getText().toString().equals("男")){
            sex=1;
        }else if(sex_et.getText().toString().equals("女")){
            sex=2;
        }else{
            sex=0;
        }
        Map<String,String> map=new HashMap<>();
        if(email!=null){
            map.put("email",email);
        }
        map.put("personalizedSignature",qianming);
        map.put("sex",sex+"");
        map.put("age",age+"");
        MyOkHttpUtils.getInstance(context).doPut(Constants.UpDataInfo,map)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        Log.i("CompleteInfo","update==="+message);
                        GetInfo();
                    }
                });
    }

    private void GetInfo() {
        MyOkHttpUtils.getInstance(context).doGet(Constants.GetInfo, null)
                .excute(new MyOkHttpUtils.OKCallBack() {
                    @Override
                    public void onFailure(String message) {

                    }

                    @Override
                    public void onResponse(String message) {
                        Log.i("CompleteInfo","message===="+message);
                        if (message != null) {
                            try {
                                JSONObject jsonObject=new JSONObject(message);
                                boolean result=jsonObject.getBoolean("result");
                                if(result){
                                    UserInfo userInfo = gson.fromJson(message, UserInfo.class);
                                    name=userInfo.getData().getRealName();
                                    age=userInfo.getData().getAge();
                                    phone=userInfo.getData().getPhone();
                                    nick_name_et.setText(name);
                                    age_et.setText(age+"");
                                    mobile_et.setText(phone);
                                    qianming=userInfo.getData().getPersonalizedSignature();
                                    email=userInfo.getData().getEmail();
                                    if(qianming!=null&&qianming.length()!=0){
                                        qianming_et.setText(qianming);
                                    }
                                    if(email!=null&&email.length()!=0){
                                        QQ_mail_et.setText(email);
                                    }
                                    sex=userInfo.getData().getSex();
                                    if(sex==0){
                                        sex_et.setText("保密");
                                    }else if(sex==1){
                                        sex_et.setText("男");
                                    }else if(sex==2){
                                        sex_et.setText("女");
                                    }
                                    avatar=userInfo.getData().getAvatar();
                                    int defaultName=userInfo.getData().getIsDefaultName();
                                    Glide.with(context)
                                            .load(new GlideUrl(Constants.DOWN_USER_PICTURE+avatar,new LazyHeaders.Builder().addHeader("WZ-AUTH-TOKEN", MyInfo.Token).addHeader("WZ-AUTH-ID",MyInfo.User_Id+"").build()))
                                            .transform(new GlideCircleTransform(context))
                                            .error(R.mipmap.default_head)
                                            .into(head_iv);
                                    SetProgress();
                                }

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }
                    }
                });
    }

    private void SetProgress(){
        int baifen=10;
        if(name!=null&&name.length()!=0){
            baifen +=10;
        }
        if(email!=null&&email.length()!=0){
            baifen +=10;
        }
        if(qianming!=null&&qianming.length()!=0){
            baifen +=40;
        }
        if(sex!=0){
            baifen +=10;
        }
        if(age!=0){
            baifen +=10;
        }
        if(avatar!=0){
            baifen +=10;
        }
        complete_progress.setText(baifen+"%");
    }

    //请求权限的返回结果
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PictureUtils.CAMERA) {
            for (int index = 0; index < permissions.length; index++) {
                switch (permissions[index]) {
                    case Manifest.permission.CAMERA:
                        if (grantResults[index] == PackageManager.PERMISSION_GRANTED) {
                            /**用户已经受权*/
                            startActivityForResult(
                                    new Intent(MediaStore.ACTION_IMAGE_CAPTURE), PictureUtils.CAMERA);
                        } else if (grantResults[index] == PackageManager.PERMISSION_DENIED) {
                            /**用户拒绝了权限*/
                            MyMethod.ShowDialog(context,"应用没有拍照权限，请授权！");
                        } else {
                            MyMethod.ShowDialog(context,"应用没有拍照权限，请授权！");
                        }
                        break;
                }
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PictureUtils.CAMERA) {
            final Bitmap bitmap = data.getParcelableExtra("data");

            String path = Environment.getExternalStorageDirectory() + File.separator + "paizhao/";
            Log.i("CompleteInfo", "path====" + path);
            File file = new File(path);
            if(!file.exists()){
                file.mkdirs();
            }
            File file1=new File(file,"image2.png");
            try {
                FileOutputStream fileOutputStream=new FileOutputStream(file1);
                bitmap.compress(Bitmap.CompressFormat.PNG,90,fileOutputStream);
                fileOutputStream.flush();
                fileOutputStream.close();
                Log.i("CompleteInfo","已经保存");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            UpImage(file1);
        }
    }

    private void UpImage(File file) {
        MyOkHttpUtils.getInstance(context).upLoadImage(Constants.UP_USER_PICTURE, file).excute(new MyOkHttpUtils.OKCallBack() {

            @Override
            public void onFailure(String message) {
                Log.i("CompleteInfo", "message=image=Fail=" + message);
            }

            @Override
            public void onResponse(String message) {
                Log.i("CompleteInfo", "message=image=Success=" + message);
                ImageJson imageJson = gson.fromJson(message, ImageJson.class);
                avatar = imageJson.getData().getId();
                Glide.with(context).load(Constants.DOWN_USER_PICTURE+avatar)
                        .error(R.mipmap.default_head).into(head_iv);
            }
        });
    }
}
